<?php


namespace app\job;

use common\service\Job;
use common\service\JobService;
use think\facade\Db;
use think\facade\Log;
use think\queue;
class Task
{
    /**
     * 任务消费类
     * @param queue\Job $job
     * @param $data
     * @return bool
     */
    public function fire(queue\Job $job, $data)
    {
        $rt = $this->doJobCreateOrder($data);
        if($rt){
            $job->delete();
            return true;
        }

        // 重试三次失败 todo...
        if($job->attempts() == 3){
            $job->delete();
            $trueFlag = JobService::pushSeckillStock(1,true,$data['goods_id']);    //失败回滚库存管理
            if ($trueFlag)
            {
                Log::info("-------------------------------------库存回滚成功！--------------------------------------------");
            }else
            {
                Log::error("-------------------------------------库存回滚失败！--------------------------------------------");
            }
            return false;
        }

        //执行失败10S后重试
        $job->release(10);
    }


    /**
     * 生成订单
     * @param $data
     * @return bool
     */
    public function doJobCreateOrder($data)
    {
        $data['expire_time'] = $data['addtime'] + 300;   //创建订单添加15分钟过期时间
        $orderId = Db::name('order')->insertGetId($data);
        var_dump($orderId);
        if ($orderId)
        {
            Log::info("-------------------------------------".$orderId."创建订单成功！--------------------------------------------");
            echo date('Y-m-d H:i:s')."\n";
            return true;
        }else
        {
            Log::error("-------------------------------------".date('Y-m-d H:i:s')."创建订单失败！--------------------------------------------");
            return false;
        }
    }

}